package com.epam.menu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class Menu {
	private final List<MenuItem> listOfMenuItems;

	public Menu(List<MenuItem> items) {
		listOfMenuItems = items;
	}

	public void run() {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));

		while (true) {
			int k=1;
			for (MenuItem item : listOfMenuItems){
				System.out.print("<"+k+"> ");
				item.printFrame();
				k++;
				}
			System.out.println();
			try {
				String commandId = reader.readLine();
				MenuItem selectedMenuItem = null;

				selectedMenuItem = searchCommand(commandId, selectedMenuItem);

				if (selectedMenuItem != null) {
					if (!selectedMenuItem.execute())
						return;
				} else
					System.out.println("No such command.");
			} catch (IOException e) {
				;
			}
		}
	}

	private MenuItem searchCommand(String commandId, MenuItem selectedMenuItem) {
		for (MenuItem item : listOfMenuItems) {
			if (commandId.equals(item.getId())) {
				selectedMenuItem = item;
				break;
			}
		}
		return selectedMenuItem;
	}
}
